package com.icesoft.core.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtil {
	private static final String DEFAULT_CHARSET = "UTF-8";

	private static final int DEF_CONN_TIMEOUT = 3000;
	private static final int DEF_READ_TIMEOUT = 30000;

	public static String get(String url) {
		try {
			return http("GET", url, null, null);
		} catch (IOException e) {
			return null;
		}
	}

	public static String post(String url, Map<String, String> bodyMap) {
		StringBuilder bodyBuilder = new StringBuilder();
		if (!bodyMap.isEmpty()) {
			for (Entry<String, String> entry : bodyMap.entrySet()) {
				bodyBuilder.append("&").append(entry.getKey()).append("=").append(entry.getValue());
			}
			bodyBuilder.deleteCharAt(0);
		}

		return post(url, bodyBuilder.toString());
	}

	public static String post(String url, String body) {
		try {
			return http("POST", url, null, body);
		} catch (IOException e) {
			return null;
		}
	}

	public static String http(String requestMethod, String url, Map<String, String> headers, String body)
			throws IOException {
		HttpURLConnection http = null;
		try {
			URL _url = new URL(url);
			http = (HttpURLConnection) _url.openConnection();
			// 连接超时
			http.setConnectTimeout(DEF_CONN_TIMEOUT);
			// 读取超时 --服务器响应比较慢，增大时间
			http.setReadTimeout(DEF_READ_TIMEOUT);
			http.setUseCaches(false);
			if (requestMethod == null) {
				requestMethod = "GET";
			}
			http.setRequestMethod(requestMethod);
			http.setRequestProperty("x-requested-with", "XMLHttpRequest");
			http.setRequestProperty("User-Agent",
					"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
			if (null != headers && !headers.isEmpty()) {
				for (Entry<String, String> entry : headers.entrySet()) {
					http.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			if (body != null) {
				OutputStream out = http.getOutputStream();
				http.setRequestProperty("Byte-Length", String.valueOf(body.length()));
				out.write(body.getBytes(DEFAULT_CHARSET));
				out.flush();
				out.close();
			}

			InputStream in = http.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
			String valueString = null;
			StringBuffer bufferRes = new StringBuffer();
			while ((valueString = read.readLine()) != null) {
				bufferRes.append(valueString);
			}
			in.close();
			return bufferRes.toString();
		} catch (IOException e) {
			throw e;
		} finally {
			if (http != null) {
				http.disconnect();// 关闭连接
			}
		}
	}

}
